package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sky.dto.UserLoginDTO;
import com.sky.dto.UserLoginDTO1;
import com.sky.entity.SysUser;
import com.sky.exception.BizException;
import com.sky.exception.ExceptionEnum;
import com.sky.mapper.SysUserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author llj
 * @since 2025-01-17
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public SysUser wxLogin(UserLoginDTO1 userLoginDTO){


        String openid = getOpenid(userLoginDTO.getCode());
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            /////////
            // TODO 上线时记得把下面代码注释取消,注释作用是为了测试,绕过openId的检查
            //throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
            openid = userLoginDTO.getCode();
        }

        //判断是否是第一次登入
        SysUser sysUser = this.getOne(new QueryWrapper<SysUser>().eq("openid", openid));
        if(sysUser == null){
            sysUser = new SysUser();
            sysUser.setOpenid(openid);
            String name = openid;
            if(openid.length()>5){
                name = openid.substring(0,5);
            }
            sysUser.setNickName(name);
            sysUserMapper.insert(sysUser);
        }


        //返回这个用户对象
        return sysUser;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
